'''
Created on Mar 27, 2011

@author: kivson
'''

from django.core import management
import e_citacao.settings as settings

management.setup_environ(settings)
from django.db.utils import IntegrityError
from django.db import connection

from e_citacao.cita.models import *


def stringMenorQue(txt, qtd = 3):

    return len(txt) < qtd

def stringMenosDeXPalavras(txt, qtd = 3):

    return txt.count(" ") + 1 < qtd

def removeTxt(txt, s1,s2):

    posW = txt.find(s1)

    while not posW == -1:

        posEspaco = txt.find(s2, posW)
        if not posEspaco == -1:
            txt = txt[:posW] + txt[posEspaco+len(s2):]

        posW = txt.find(s1, posW + 1)



    return txt


def removeIntervalo(s1, s2):

    todasCitacoes = Citacao.objects.all()

    citacoesComW = todasCitacoes.filter(texto__contains = s1)

    total = 0
    for c in citacoesComW:


        print c.texto
        c.texto = removeTxt( c.texto, s1, s2)
        try:
            c.save()
        except IntegrityError, e:
            print "Erro: " + str(c)
            connection.close()
            if c.texto == todasCitacoes.filter(texto = c.texto)[0].texto:
                c.delete()

        print c

        total += 1

    print len(citacoesComW)




def removerPorFuncao(fun, *args, **kargs):

    todasCitacoes = Citacao.objects.all()
    for c in todasCitacoes:
        if fun(c.texto, *args, **kargs ):
            print c, c.autor
            c.delete()

def removePalavra(de, para = ""):
    citacoes = Citacao.objects.all().filter(texto__contains = de)
    for c in citacoes:
        c.texto = c.texto.replace(de, para)
        print c, "----", c.autor
        #c.save()

def removeComTxt(txt):
    citacoes = Citacao.objects.all().filter(texto__contains = txt)
    for c in citacoes:
        print c, "----", c.autor
        #c.delete()
    print len(citacoes)

def main():
    #removeIntervalo("http://", " ")
    #removeIntervalo("http://", '."')
    #removeIntervalo("<ref>", "</ref>")
    #removeIntervalo("<ref", ">")
    #removeIntervalo("w:","|")

    #removerPorFuncao(stringMenorQue, qtd = 15)
    #removerPorFuncao(stringMenosDeXPalavras, qtd = 4)

    #removeComTxt("Quem:")
    #removeComTxt("{{L")
    #removeComTxt("Especial:")
    removeComTxt("{{")

if __name__ == '__main__':
    main()